package com.velvetantler.weather.view.login

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.MapsInitializer
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.velvetantler.weather.MainActivity
import com.velvetantler.weather.WeatherGlobal
import com.velvetantler.weather.base.BaseBindingActivity
import com.velvetantler.weather.bean.LoginRequest
import com.velvetantler.weather.constants.Constants
import com.velvetantler.weather.databinding.AcLoginBinding
import com.velvetantler.weather.utils.PreferenceUtil
import com.velvetantler.weather.utils.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : BaseBindingActivity<AcLoginBinding>() {

    private val TAG = "LoginActivity"

    /**
     * 获取位置 经纬度
     */
    fun getLocation() {
        // 更新隐私合规状态,需要在初始化地图之前完成
        MapsInitializer.updatePrivacyShow(this, true, true);
        // 更新同意隐私状态,需要在初始化地图之前完成
        MapsInitializer.updatePrivacyAgree(this, true);
        // 初始化定位客户端
        val locationClient = AMapLocationClient(this)
        // 初始化定位客户端的配置
        val setLocationOption = AMapLocationClientOption()
        setLocationOption.isOnceLocation = true // 只获取一次位置信息
        setLocationOption.isLocationCacheEnable = false // 不使用缓存
        locationClient.setLocationOption(setLocationOption)
        // 设置定位监听，定位回调处理逻辑
        locationClient.setLocationListener { location: AMapLocation? ->
            Toast.makeText(this, "城市名：${location?.city}", Toast.LENGTH_SHORT).show()
            // 保存经纬度
            WeatherGlobal.setLatitude(location!!.latitude.toString())
            WeatherGlobal.setLongitude(location.longitude.toString())
            // 获取城市名称并保存
            getCityName(location.latitude, location.longitude)
        }
        // 开始定位
        locationClient.startLocation()
    }

    fun getCityName(latitude: Double, longitude: Double) {
        val geocodeSearch = GeocodeSearch(this)
        geocodeSearch.setOnGeocodeSearchListener(object :
            GeocodeSearch.OnGeocodeSearchListener {
            override fun onRegeocodeSearched(
                result: RegeocodeResult?,
                rCode: Int
            ) {
                // 通过坐标查地址的结果
                WeatherGlobal.setCityName(result!!.regeocodeAddress.city)
            }

            override fun onGeocodeSearched(
                p0: GeocodeResult?,
                p1: Int
            ) {
                // 通过地址查座标的结果
            }
        })
        val point = LatLonPoint(latitude, longitude)
        val query = RegeocodeQuery(point, 50F, GeocodeSearch.AMAP)
        geocodeSearch.getFromLocationAsyn(query)
    }

    /**
     * 权限申请官推新方式
     */
    private val requestLocationPermission = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) {
        Log.i(TAG, "onActivityResult: $it")
        if (it) {
            // 获取权限成功
            Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show()
            getLocation()
        } else {
            // 获取权限失败
            Toast.makeText(this, "授权失败！", Toast.LENGTH_SHORT).show()
        }
    }

    fun checkAndRequestPermission() {
        // 1. 检查系统是否有对应权限
        val hasLocationPermission =
            ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION")
        if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) { // 0 表示权限被授予 -1 表示权限被拒绝
            // 2. 请求权限
//            // ①传统办法
//            ActivityCompat.requestPermissions(
//                this, // context
//                arrayOf("android.permission.ACCESS_COARSE_LOCATION"), // 权限列表
//                1 // 请求码，相当于于标识该权限申请的ID
//            )
            // ②AndroidX 官方推荐方法
            requestLocationPermission.launch("android.permission.ACCESS_COARSE_LOCATION")
        } else {
            getLocation()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 检查权限
        checkAndRequestPermission()

        // 获取登录按钮
        binding.tvLogin.setOnClickListener {
            doLogin()
        }
    }

    /**
     * 权限申请传统办法
     */
//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String?>,
//        grantResults: IntArray,
//        deviceId: Int
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults, deviceId)
//        if (requestCode == 1) {
//            if (grantResults[0] == 0) {
//                // 权限被授予
//                Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show()
//            } else {
//                // 权限被拒绝
//                Toast.makeText(this, "授权失败！", Toast.LENGTH_SHORT).show()
//            }
//        }
//    }

    fun doLogin() {
        // 获取账号和密码
        val account = binding.etUsername.text.toString()
        val password = binding.etPassword.text.toString()
        // 判空
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show()
            return
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show()
            return
        }

        // 开协程，调用登录接口
        try {
            lifecycleScope.launch(Dispatchers.Main) {
                val req = LoginRequest(account, password)
                val res = withContext(Dispatchers.IO) {
                    RetrofitClient.apiServices.login(req)
                }
                if (res.code == 10000) {
                    // 保存token
                    val token = res.data.token
                    Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_SHORT).show()
                    // 保存token到SharedPreferences
                    PreferenceUtil.getInstance(this@LoginActivity)
                        .setValue(Constants.TOKEN_PREF_KEY, token)
                    // 跳转到MainActivity
                    var intent = Intent(this@LoginActivity, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 自动绑定Activity和XML
     */
    override fun initBinding(layoutInflater: LayoutInflater): AcLoginBinding {
        return AcLoginBinding.inflate(layoutInflater)
    }

}